// pages/merchant/home/home.js
import { baseUrl, baseWebsocketUrl } from '../../../api/request.js';
import { EventBusInstance } from '../../../utils/eventBus.js';

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cardCur: 0,
    swiperList: [{
      id: 0,
      type: 'image',
      url: 'https://hotel-booking-min.oss-cn-shanghai.aliyuncs.com/swipper-1.jpg'
    }, {
      id: 1,
      type: 'image',
      url: 'https://hotel-booking-min.oss-cn-shanghai.aliyuncs.com/swipper-2.jpg',
    }, {
      id: 2,
      type: 'image',
      url: 'https://hotel-booking-min.oss-cn-shanghai.aliyuncs.com/swipper-3.jpg',
    }, {
      id: 3,
      type: 'image',
      url: 'https://hotel-booking-min.oss-cn-shanghai.aliyuncs.com/swipper-4.jpg',
    }],
  },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.towerSwiper('swiperList');
    // 初始化towerSwiper 传已有的数组名即可
    
    wx.onSocketOpen(resp => {
      app.globalData.websocketConnected = true;
      this.data.intervalId = setInterval(() => {
        wx.sendSocketMessage({
          data: 'ping',
        });
      }, 5000);
    });

    wx.onSocketError(err => {
      console.log('websocket错误', err);
    });

    wx.onSocketClose(resp => {
      console.log('连接关闭');
      app.globalData.websocketConnected = false;
      clearInterval(this.data.intervalId);
      this.data.intervalId = null;

      this.reconnect();
    });

    wx.onSocketMessage(data => {
      //console.log(data);
      if ('pong' === data.data) {
        this.data.heartbeatTime = new Date().getTime();
        return;
      }
      EventBusInstance.emit('chat', JSON.parse(data.data));
    });

    this.reconnect();
    setInterval(() => {
      if (this.data.heartbeatTime && (new Date().getTime() - this.data.heartbeatTime > 20000)) {
        app.globalData.websocketConnected = false;
        clearInterval(this.data.intervalId);
        this.data.intervalId = null;

        this.reconnect();
      }
    }, 15000);
  },

  reconnect() {
    if (app.globalData.websocketConnected) {
      wx.closeSocket();
    }

    const token = app.globalData.token;
    return wx.connectSocket({
      url: `${baseWebsocketUrl}/websocket/endpoint/${app.globalData.currentUserInfo.id}`,
      header: {
        'X-Auth-Token': token
      },
      timeout: 5000
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  DotStyle(e) {
    this.setData({
      DotStyle: e.detail.value
    })
  },
  // cardSwiper
  cardSwiper(e) {
    this.setData({
      cardCur: e.detail.current
    })
  },

  // towerSwiper
  // 初始化towerSwiper
  towerSwiper(name) {
    let list = this.data[name];
    for (let i = 0; i < list.length; i++) {
      list[i].zIndex = parseInt(list.length / 2) + 1 - Math.abs(i - parseInt(list.length / 2))
      list[i].mLeft = i - parseInt(list.length / 2)
    }
    this.setData({
      swiperList: list
    })
  },

  // towerSwiper触摸开始
  towerStart(e) {
    this.setData({
      towerStart: e.touches[0].pageX
    })
  },
  // towerSwiper计算方向
  towerMove(e) {
    this.setData({
      direction: e.touches[0].pageX - this.data.towerStart > 0 ? 'right' : 'left'
    })
  },
  // towerSwiper计算滚动
  towerEnd(e) {
    let direction = this.data.direction;
    let list = this.data.swiperList;
    if (direction == 'right') {
      let mLeft = list[0].mLeft;
      let zIndex = list[0].zIndex;
      for (let i = 1; i < list.length; i++) {
        list[i - 1].mLeft = list[i].mLeft
        list[i - 1].zIndex = list[i].zIndex
      }
      list[list.length - 1].mLeft = mLeft;
      list[list.length - 1].zIndex = zIndex;
      this.setData({
        swiperList: list
      })
    } else {
      let mLeft = list[list.length - 1].mLeft;
      let zIndex = list[list.length - 1].zIndex;
      for (let i = list.length - 1; i > 0; i--) {
        list[i].mLeft = list[i - 1].mLeft
        list[i].zIndex = list[i - 1].zIndex
      }
      list[0].mLeft = mLeft;
      list[0].zIndex = zIndex;
      this.setData({
        swiperList: list
      })
    }
  },
  navigate(e) {
    const destination = e.currentTarget.dataset.destination;
    if (e.currentTarget.dataset.destination === 'findOrder') {
      wx.navigateTo({
        url: '/pages/merchant/order/findOrder',
      })
    } else if (e.currentTarget.dataset.destination === 'orderList') {
      wx.navigateTo({
        url: '/pages/merchant/order/orderList',
      })
    } else if (e.currentTarget.dataset.destination === 'chatList') {
      wx.navigateTo({
        url: '/pages/chat/chatList',
      })
    } else if (e.currentTarget.dataset.destination === 'wallet') {
      wx.navigateTo({
        url: '/pages/wallet/wallet',
      })
    } else if (e.currentTarget.dataset.destination === 'profile') {
      wx.navigateTo({
        url: '/pages/profile/profile',
      })
    } else if (e.currentTarget.dataset.destination === 'endOrder') {
      wx.showToast({
        title: '活动未开始，敬请期待',
        icon: 'none',
        duration: 2000
      })
    } else if (e.currentTarget.dataset.destination === 'customerService') {
      wx.showToast({
        title: '客服未上线，请稍后再试',
        icon: 'none',
        duration: 2000
      })
    }
  }
})